#include <iostream>
#include <cstring>

using std::cout;
using std::endl;
using std::istream;
using std::ostream;

/*
SSO思想:
    小于等于 15 个有效字节的字符串直接放到对象中
    大于 15 个有效字节的字符串放在堆上
    所有的拷贝操作都是深拷贝，不存在浅拷贝
*/

class String 
{
friend ostream & operator<<(ostream & os,const String & rhs);

    union Buffer{
        char* _pointer;
        char _local[16];
    };
public:
    String(const char * pstr);
    ~String();
    char & operator[](size_t idx);
    const char & operator[](size_t idx) const;
private:
	size_t _size;
	size_t _capacity;
    Buffer _buffer;
};

// 有参构造函数
String::String(const char* pstr)
    : _size(strlen(pstr))
    , _capacity(15){
    if(_size > 15){
        _buffer._pointer = new char[_size + 1] ();
        strcpy(_buffer._pointer, pstr);
        _capacity = _size;
    }else{
        strcpy(_buffer._local, pstr);
    }
}

// 析构函数
String::~String(){
    if(_size > 15 && _buffer._pointer != nullptr){
        delete [] _buffer._pointer;
        _buffer._pointer = nullptr;
    }
}

// 输出流运算符重载
ostream& operator<<(ostream& os,const String& rhs){
    if(rhs._size > 15){
        os << rhs._buffer._pointer;
    }else{
        os << rhs._buffer._local;
    }
    return os;
}

// [] 重载
char& String::operator[](size_t idx){
    if(idx >= _size){
        throw "访问越界";
    }
    if(_size > 15){
        return _buffer._pointer[idx];
    }else{
        return _buffer._local[idx];
    }
}
const char& String::operator[](size_t idx) const{
    if(idx >= _size){
        throw "访问越界";
    }
    if(_size > 15){
        return _buffer._pointer[idx];
    }else{
        return _buffer._local[idx];
    }
}


// 实现以下函数，简单模拟SSO思想的string并验证实现效果
int main(void)
{
    String str1("hello");
    String str2("hello,world!!!!!");

    printf("%p\n", &str1[0]);
    printf("%p\n", &str2[0]);
    return 0;
}